package com.dwj.auto.comment.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dwj.auto.comment.common.response.PageResponse;
import com.dwj.auto.comment.common.response.Response;
import com.dwj.auto.comment.common.utils.CodeUtil;
import com.dwj.auto.comment.config.mybatis.plus.CommonServiceImpl;
import com.dwj.auto.comment.dao.entity.StuClass;
import com.dwj.auto.comment.dao.entity.Student;
import com.dwj.auto.comment.dao.entity.UserRole;
import com.dwj.auto.comment.dao.mapper.StuClassMapper;
import com.dwj.auto.comment.dao.mapper.StudentMapper;
import com.dwj.auto.comment.model.dto.StudentClassDto;
import com.dwj.auto.comment.model.form.StudentForm;
import com.dwj.auto.comment.model.req.StuSearchCriteria;
import com.dwj.auto.comment.model.req.StudentCriteria;
import com.dwj.auto.comment.model.vo.StudentSearchVo;
import com.dwj.auto.comment.model.vo.StudentVo;
import com.dwj.auto.comment.model.vo.UserVo;
import com.dwj.auto.comment.service.IStuClassService;
import com.dwj.auto.comment.service.IStudentService;
import com.dwj.auto.comment.service.IUserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static com.dwj.auto.comment.common.constant.RedisKey.Student.DOMAIN;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dwjian
 * @since 2020-01-13
 */
@Service
public class StudentServiceImpl extends CommonServiceImpl<StudentMapper, Student> implements IStudentService {

    @Resource
    private StuClassMapper stuClassMapper;
    @Resource
    private IStudentService studentService;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IStuClassService stuClassService;

    @Override
    public PageResponse<StudentVo> getList(StudentCriteria criteria) {
        IPage<StudentVo> list = baseMapper.getList(criteria.buildPage(), criteria);
        return PageResponse.success(list);
    }

    @Override
    public Response<String> edit(StudentForm form) {
        if(StringUtils.isEmpty(form.getId())){
            return add(form);
        }
        Student student = new Student();
        BeanUtils.copyProperties(form, student);
        boolean update = this.updateById(student);
        if(update) {
            return Response.success();
        }
        return Response.fail("更新失败");
    }

    @Override
    public Response<String> delete(List<String> ids) {
        List<Student> collect = ids.stream().map(v -> new Student().setId(v).setIsDel(1)).collect(Collectors.toList());
        boolean batch = this.updateBatchById(collect);
        if(batch) {
            return Response.success("删除成功");
        }
        return Response.fail("删除失败");
    }

    @Override
    public Response<StudentVo> get(String id) {
        Student student = lambdaQuery().eq(Student::getId, id).one();
        if(student != null && student.getIsDel() != 1){
            StudentVo studentVo = new StudentVo();
            BeanUtils.copyProperties(student, studentVo);
            StuClass stuClass = stuClassMapper.selectById(student.getClassId());
            StudentClassDto studentClassDto = new StudentClassDto();
            BeanUtils.copyProperties(stuClass, studentClassDto);
            studentVo.setStuClass(studentClassDto);
            return Response.success(studentVo);
        }else {
            return Response.fail("该学生已被删除，请刷新页面");
        }
    }

    @Override
    public PageResponse<StudentSearchVo> searchList(StuSearchCriteria criteria) {
        return PageResponse.success(baseMapper.searchList(criteria.buildPage(), criteria));
    }

    @Override
    public boolean hasStudent(UserVo userVo) {
        List<UserRole> userRoleList = userRoleService.lambdaQuery().eq(UserRole::getUserId, userVo.getId()).eq(UserRole::getIsDel,0).list();
        if(CollectionUtil.isNotEmpty(userRoleList)){
            Object[] roleIds = userRoleList.stream().map(UserRole::getId).toArray();
            List<StuClass> stuClasses = stuClassService.lambdaQuery().in(StuClass::getTeacherId, roleIds).eq(StuClass::getIsDel, 0).list();
            if(CollectionUtil.isNotEmpty(stuClasses)){
                Object[] classIds = stuClasses.stream().map(StuClass::getId).toArray();
                Integer count = studentService.lambdaQuery().in(Student::getClassId, classIds).eq(Student::getIsDel, 0).count();
                return count != null && count > 0;
            }
        }
        return false;
    }

    /**
     * 新增学生
     * @param form
     * @return
     */
    private Response<String> add(StudentForm form){
        Student student = new Student();
        BeanUtils.copyProperties(form, student);
        student.setId(CodeUtil.uuid());
        student.setStuCode(CodeUtil.generateCode(DOMAIN, 8));
        boolean add = this.save(student);
        if(add) {
            return Response.success();
        }
        return Response.fail("新增失败");
    }
}
